from django.shortcuts import render
from django.http import JsonResponse
from django.core.paginator import Paginator, InvalidPage
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from teachers.serializer import TeacherSerial
from .models import Teachers
from .forms import AddTeacher
# Create your views here.


class AddTeacherView(APIView):

    def get(self, request):
        form_data = AddTeacher()
        return render(request, "add_teacher.html", locals())

    def post(self, request):
        teacher_serial = TeacherSerial(data=request.data, context={"request": request})
        if teacher_serial.is_valid():
            teacher_serial.save()
            return Response(teacher_serial.data, status=status.HTTP_201_CREATED)
        else:
            return Response(teacher_serial.errors, status=status.HTTP_400_BAD_REQUEST)



class TeachersListView(APIView):

    def get(self, request, page=20, offset=1):
        print(request.GET)
        teachers = Teachers.get_all()
        paginator = Paginator(teachers, page)
        try:
            data = paginator.page(offset)
        except InvalidPage:
            data = paginator.page(1)
        return render(request, "teachers.html", locals())



class TeacherQueryView(APIView):

    def get(self, request):
        filters = {
            "name": request.GET.get("name"),
            "experience": request.GET.get("experience"),
            "gender": request.GET.get("gender"),
        }
        teacher = Teachers.get_list_by_query(**filters)
        data = []
        for obj in teacher:
            data.append({
                "id": obj.id,
                "name": obj.name,
                "experience": obj.experience,
                "info": obj.info,
            })
        return JsonResponse({"res": data})


class TeacherDetailView(APIView):

    def get(self, request, pk):
        teacher = Teachers.get_one(pk)
        ser = TeacherSerial(teacher)
        return Response(ser.data)

    def put(self, request, pk):
        teacher = Teachers.get_one(pk)
        ser = TeacherSerial(teacher, data=request.data)
        print(ser)
        if ser.is_valid():
            ser.save()
            return Response(status=status.HTTP_202_ACCEPTED)
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk):
        teacher = Teachers.get_one(pk)
        if not teacher:
            return Response(status=status.HTTP_404_NOT_FOUND)
        teacher.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)